﻿using System.Windows;
using Baosight.ZNH.ZMCommon;
using Baosight.ZNH.ZMCommon.ChildWindows;
using Baosight.Platform.Core;
using System.Collections.Generic;
using Baosight.Platform.Core.UI.Controls;
using Baosight.Platform.Core.ServiceModel;

namespace Baosight.ZNH.ZMCM.UI.ChildWindows
{
    public partial class ImportMaterialHCGSInsert : EFViewCmes
    {
        private static string SUCCESS_FLAG = "success";

        public ImportMaterialHCGSInsert()
        {
            InitializeComponent();
            base.Mode = OperationMode.Insert;
        }

        /// <summary>
        /// 下一步按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Next_Click(object sender, RoutedEventArgs e)
        {
            string validate_result = ValidateGridData();
            if (!validate_result.Equals(SUCCESS_FLAG))
            {
                base.OpenEFWindowAlert(validate_result, true);
                return;
            }

            CalculateReduceNumber();

            List<EIRow> rows = this.grid.GetCheckedEIRows();
            string fdResourceNoteCode = "";
            foreach (EIRow grid_row in rows)
            {
                if (!fdResourceNoteCode.Contains(grid_row["fdNoteCode"].ToString()))
                {
                    fdResourceNoteCode += grid_row["fdNoteCode"].ToString();
                }
            }

            this.fdResourceNoteCode.Value = fdResourceNoteCode;

            //隐藏上帧页面
            this.RESULT.Visibility = Visibility.Collapsed;//主表录入
            this.Next.Visibility = Visibility.Collapsed;  //下一步按钮
            this.Return.Visibility = Visibility.Collapsed; //返回按钮
            this.INQU.Visibility = Visibility.Collapsed;//查询区域

            //展示下帧页面
            this.InsertGrid.Visibility = Visibility.Visible;
            this.Commit.Visibility = Visibility.Visible;
            this.Cancel.Visibility = Visibility.Visible;
        }

        /// <summary>
        /// 关闭按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Return_Click(object sender, RoutedEventArgs e)
        {
            CmesWindows _window = this.Parent as CmesWindows;
            _window.DialogResult = false;
            _window.Close();
        }

        /// <summary>
        /// 下一步中确定按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Commit_Click(object sender, RoutedEventArgs e)
        {
            if (this.InsertGrid.ValidateField())
            {
                EIInfo eiInfo = new EIInfo();
                eiInfo.Set("service", "ZMCMB3");
                eiInfo.Set("method", "minusEvaluation");

                NoteBlock(eiInfo);
                ResultBlock(eiInfo);

                HttpServiceAgent agent = new HttpServiceAgent();
                agent.CallService(eiInfo, OnDoWorkCompleted);
            }

        }

        /// <summary>
        /// 下一步中关闭按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            CmesWindows _window = this.Parent as CmesWindows;
            _window.DialogResult = false;
            _window.Close();
        }

        /// <summary>
        /// 新增后的回调方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnDoWorkCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            EIInfo inInfo = e.EIInfo;
            if (inInfo.Status == -1)
            {
                this.TempButtonOpen(true);
                this.OnCommitMessagePopup(inInfo);//操作失败，消息提醒
            }
            else
            {
                CmesWindows _window = this.Parent as CmesWindows;
                _window.DialogResult = true;
                _window.Close();
            }
        }

        /// <summary>
        /// 验证列表中已勾选数据的数据格式等
        /// </summary>
        /// <returns></returns>
        private string ValidateGridData()
        {
            List<EIRow> allCheckContent = this.grid.GetCheckedEIRows();

            if (allCheckContent.Count <= 0)
            {
                return "请勾选需要冲估的入库明细！";
            }

            foreach (EIRow row in allCheckContent)
            {
                if (row["fdInvoiceSum"] == null || row["fdInvoiceSum"].Equals(""))
                {
                    return "发票金额不允许为空！";
                }

                if (row["fdActualNumber"] == null || row["fdActualNumber"].Equals(""))
                {
                    return "实进数量不允许为空！";
                }

                if (row["fdInvoice"] == null || row["fdInvoice"].Equals(""))
                {
                    return "发票号不允许为空！";
                }

                if (row["fdInvoice"].ToString().Length >= 25)
                {
                    return "发票号可输入25个字符！";
                }

                try
                {
                    double invoiceSum = double.Parse(row["fdInvoiceSum"].ToString());
                    double newNumber = double.Parse(row["fdActualNumber"].ToString());
                    double oldNumber = double.Parse(row["fdResourceNumber"].ToString());

                    if (newNumber == 0)
                    {
                        return "实进数量不允许为0";
                    }

                    string str_reduceNumber = "0";
                    if (row["fdReduceNumber"] != null && !row["fdReduceNumber"].Equals(""))
                    {
                        str_reduceNumber = row["fdReduceNumber"].ToString();
                    }

                    double reduceNuber = double.Parse(str_reduceNumber);

                    //if (newNumber.CompareTo(oldNumber) > 0)
                    //{
                    //    return "实进数量大于原单数量";
                    //}

                    if ((newNumber).CompareTo(oldNumber - reduceNuber) > 0)
                    {
                        //return "实进数量大于原单数量减去已冲数量";
                        row["fdExceedNumber"] = newNumber + reduceNuber - oldNumber;
                    }
                }
                catch
                {
                    return "发票金额或实进数量仅可输入小数点前10位，小数点后5位的数字！";
                }
            }

            return SUCCESS_FLAG;
        }

        /// <summary>
        /// 计算已冲数量
        /// </summary>
        private void CalculateReduceNumber()
        {
            List<EIRow> allCheckContent = this.grid.GetCheckedEIRows();

            foreach (EIRow row in allCheckContent)
            {
                double newNumber = double.Parse(row["fdActualNumber"].ToString());
                double oldNumber = double.Parse(row["fdResourceNumber"].ToString());
                string str_reduceNumber = "0";
                if (row["fdReduceNumber"] != null && !row["fdReduceNumber"].Equals(""))
                {
                    str_reduceNumber = row["fdReduceNumber"].ToString();
                }

                double reduceNuber = double.Parse(str_reduceNumber);

                if ((reduceNuber + newNumber).CompareTo(oldNumber) > 0)
                {
                    row["fdReduceNumber"] = row["fdResourceNumber"].ToString();
                }
                else
                {
                    row["fdReduceNumber"] = (reduceNuber + newNumber).ToString();
                }
            }
        }

        /// <summary>
        /// 将单据信息时单据信息组织成一个block
        /// </summary>
        /// <param name="eiInfo"></param>
        private void NoteBlock(EIInfo eiInfo)
        {
            EFViewCmesProperty _view = new EFViewCmesProperty();
            _view.DataFields = this.InsertGrid.GetChildObjects<EFDataField>(null, true);
            base.ViewProperty = _view;

            EIBlock noteBlock = new EIBlock("noteBlock");
            noteBlock.SetColumns(base.GetDataFieldColumns("noteBlock"));
            noteBlock.AddRow(base.GetDataFieldValues("noteBlock"));
            eiInfo.AddBlock(noteBlock);
        }

        /// <summary>
        /// 将列表中的记录组织成一个block
        /// </summary>
        /// <param name="eiInfo"></param>
        private void ResultBlock(EIInfo eiInfo)
        {
            EIBlock resultBlock = new EIBlock("result");
            resultBlock.SetColumns(this.grid.EIBlock.GetColumns());
            resultBlock.SetRows(this.grid.GetCheckedEIRows());
            eiInfo.AddBlock(resultBlock);
        }

        private void QueryClick(object sender, RoutedEventArgs e)
        {
            EIInfo eiInfo = new EIInfo();
            eiInfo.Set("service", "ZMCMB3");
            eiInfo.Set("method", "query");
            EIBlock block = eiInfo.AddBlock(EIConstants.QueryStatusBlock);
            EIColumn column1 = new EIColumn();
            column1.SetName("fdImportmaterialId");
            block.AddColumn(column1);

            EIRow row = new EIRow();
            row.Add("fdImportmaterialId", this.fdImportmaterialId.Value);
            block.AddRow(row);
            if (this.fdMaterialName.Value != null && !this.fdMaterialName.Value.Equals(""))
            {
                EIColumn column = new EIColumn();
                column.SetName("fdMaterialName");
                block.AddColumn(column);

                
                row.Add("fdMaterialName", this.fdMaterialName.Value);
                block.AddRow(row);
            }
            if (this.fdMaterialCode.Value != null && !this.fdMaterialCode.Value.Equals(""))
            {
                EIColumn column = new EIColumn();
                column.SetName("fdMaterialCode");
                block.AddColumn(column);

                row.Add("fdMaterialCode", this.fdMaterialCode.Value);
                block.AddRow(row);
            }
            if (this.fdSpecModel.Value != null && !this.fdSpecModel.Value.Equals(""))
            {
                EIColumn column = new EIColumn();
                column.SetName("fdSpecModel");
                block.AddColumn(column);

                row.Add("fdSpecModel", this.fdSpecModel.Value);
                block.AddRow(row);
            }
            if (this.fdProvideDepartment.Value != null && !this.fdProvideDepartment.Value.Equals(""))
            {
                EIColumn column = new EIColumn();
                column.SetName("fdProvideDepartment");
                block.AddColumn(column);

                row.Add("fdProvideDepartment", this.fdProvideDepartment.Value);
                block.AddRow(row);
            }

            HttpServiceAgent agent = new HttpServiceAgent();
            agent.CallService(eiInfo, OnDoQueryCompleted);
        }

        /// <summary>
        /// 查询后的回调方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnDoQueryCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.GetStatus() != -1)
            {
                this.grid.UpdateData(e.EIInfo);
            }
        }
    }
}
